package com.leyou.auth.config;

import com.leyou.auth.util.JwtUtils;
import com.leyou.auth.util.RsaUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;

import javax.annotation.PostConstruct;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;

@Slf4j
@Data
@ConfigurationProperties(prefix = "ly.jwt")
public class JwtProperties {

    private String secret;
    private String pubKeyPath;
    private String priKeyPath;
    private int expire;
    private String cookieName;

    private PublicKey publicKey;        // 公钥
    private PrivateKey privateKey;      // 私钥

    // 对象实例化后，读取公钥、私钥
    @PostConstruct
    public void init() throws Exception {

        File pubKey = new File(pubKeyPath);
        File priKey = new File(priKeyPath);
        // 若不存在，生成密钥
        if (!pubKey.exists() || !priKey.exists()) {
            log.info("[配置初始化] 生成密钥");
            RsaUtils.generateKey(pubKeyPath, priKeyPath, secret);
        }

        // 读取公钥，私钥
        this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
        this.privateKey = RsaUtils.getPrivateKey(priKeyPath);
    }
}
